﻿using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace biaoqian.CSwnjian
{
    public class CHK
    {
        LDhuoyunEntities db = new LDhuoyunEntities();
        public DataTable HESUO()
        {
            DataTable da = new DataTable();
            da.Columns.Add("GM_PART_NUM");//物料名称
            da.Columns.Add("ACD_PART_NUM");//年周
            da.Columns.Add("QTY");//数量
            da.Columns.Add("A3421");// 18位码 MP501CN1+1+2249+0001
            da.Columns.Add("TIEM_DESC_US");// 1；1524-0C760WP ；空白；空白；16；21/32：空白
            return da;
        }
        public DataTable JUDN()
        {
            DataTable da = new DataTable();
            da.Columns.Add("GM_PART_NUM");//物料名称
            da.Columns.Add("ACD_PART_NUM");//年周
            da.Columns.Add("QTY");//数量
            da.Columns.Add("A3421");// 18位码 MP501CN1+1+2249+0001
            da.Columns.Add("TIEM_DESC_US");// 1；1524-0C760WP ；空白；空白；16；21/32：空白
            da.Columns.Add("XiangH");// 1；1524-0C760WP ；空白；空白；16；21/32：空白
            return da;
        }
        public DataTable HEsuo(DataTable dt, string qty = "0")
        {
            DataTable ShuB = HESUO();
            //数量/qty
            DataRow row = dt.Rows[0];
            var SUN = int.Parse(row["quantity"].ToString());
            var PL = Math.Ceiling((double)SUN / int.Parse(qty));
            var name = row["FSaleO"].ToString();//名称
            var GOng = row["Shipping"].ToString();//名称
            var R = row["SHIjian"].ToString();
            var N = DateTime.Parse(R).Year % 100;
            int W = Week(R);
            var shu = N + W.ToString();//周
            var CunZ = db.BIAOQIAN_C.Where(s => s.Gongshi == GOng && s.NIANZ == shu).FirstOrDefault();
            var MIAJ = CunZ == null ? 1 : int.Parse(CunZ.SHUL);
            var shh = "";
            for (int i = 0; i < PL; i++)
            {
                shh = MIAJ < 10 ? "000" : MIAJ < 100 ? "00" : MIAJ < 1000 ? "0" : "";
                var shund = "MP501CN11" + shu.ToString() + shh + MIAJ.ToString();
                MIAJ++;
                ShuB.Rows.Add(name, shu, qty, shund);
            }
            if (CunZ == null)
            {
                var B = new BIAOQIAN_C()
                {
                    Gongshi = GOng,
                    NIANZ = shu,
                    SHUL = MIAJ.ToString(),
                };
                db.BIAOQIAN_C.Add(B);
                db.SaveChanges();
            }
            else
            {
                CunZ.SHUL = MIAJ.ToString();
                db.Entry(CunZ).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            return ShuB;
        }

        private static int Week(string R)
        {
            int W;
            GregorianCalendar gc = new GregorianCalendar();
            W = gc.GetWeekOfYear(DateTime.Parse(R), CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            return W;
        }

        internal DataTable Lixun(DataTable dt, string qTY)
        {
            DataTable ShuB = JUDN();
            //数量/qty
            DataRow row = dt.Rows[0];
            var SUN = int.Parse(row["quantity"].ToString());//数量
            var PL = Math.Ceiling((double)SUN / int.Parse(qTY));//次数
            var name = row["FSaleO"].ToString();//物料名称
            var GOng = row["Material"].ToString();//名称
            var str = Regex.Replace(GOng, @"[\u4e00-\u9fa5]", ""); //去除汉字
            var PSC = row["Unit"].ToString() + "/包";//计量单位
            var R = row["SHIjian"].ToString();//时间
            var N = DateTime.Parse(R).Year.ToString();
            var Y = DateTime.Parse(R).Month.ToString();
            var RI = DateTime.Parse(R).Day.ToString();
            var HU = N + Y + RI;
            var MIAJ = 1;
            for (int i = 0; i < PL; i++)
            {
                var shund = "1008962000000000 " + MIAJ;
                MIAJ++;
                ShuB.Rows.Add(name, HU, qTY, shund, PSC, str);
            }
            return ShuB;
        }

        internal DataTable MPS(DataTable dt, string qTY)
        {
            DataTable ShuB = JUDN();
            //数量/qty
            DataRow row = dt.Rows[0];
            var SUN = int.Parse(row["quantity"].ToString());
            var PL = Math.Ceiling((double)SUN / int.Parse(qTY));//次数
            var name = row["FSaleO"].ToString();//物料名称
            var R = row["SHIjian"].ToString();
            var N = DateTime.Parse(R).ToString("yyyy.M.dd");//日期
            var GGG= row["Material"].ToString();//代码
            var Dai= row["specification"].ToString();//规格
            var PSC = row["Unit"].ToString() + "/包";//计量单位
            ShuB.Rows.Add(name, GGG, qTY, PSC,N, Dai);
            return ShuB;
        }
        public DataTable Shai()
        {
            DataTable da = new DataTable();
            da.Columns.Add("GM_PART_NUM");//料号
            da.Columns.Add("ACD_PART_NUM");//订单号
            da.Columns.Add("QTY");//数量
            da.Columns.Add("A3421");// 单位
            da.Columns.Add("TIEM_DESC_US");//日期
            da.Columns.Add("XiangH");// 空白
            da.Columns.Add("MPN");// MPN
            da.Columns.Add("REV");// PEV
            return da;
        }
        internal DataTable SiHai(DataTable dt, string qTY)
        {
            DataTable ShuB = Shai();
            //返回编码和料号
            DataRow row = dt.Rows[0];
            var bian = row["encoding"].ToString();
            var liao = row["FMaterial"].ToString();
            var Kehu = row["Shipping"].ToString();
            //调用webapi 返回数据
            K3CloudApi client = new K3CloudApi();
            //业务对象标识
            string formId = "SAL_DELIVERYNOTICE";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例 PO号=》 F_land_Text
            string fieldKeys = "FBillNo,FCustomerID.FName,FMaterialID.FNumber,F_land_Text,FMateriaModel,FQty,FPriceUnitId.FName,FDate,FCustMatID.FNumber";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式  and FCancelStatus='A'  and FPlanDeliveryDate >'" + currentDateTime + "'
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = "FCustomerID.FName='"+ Kehu + "'and FMaterialID.FNumber like'%" + liao + "%' and FBillNo like '%" + bian + "%'",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 120,
                OrderString = "FBillNo",
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());
            foreach (var item in result)
            {
                var R = DateTime.Parse(item[7].ToString()).ToString("yyyy.MM.dd");//日期
                var AC12 = item[6].ToString() + "/包";//单位
                if (item[6].ToString()=="卷")
                {
                    AC12 = "米";
                    qTY = 884.ToString();
                }
                //mpn  pev 判断
                var SHNJ = item[8].ToString();
                string ZZZB = "(LFNK|-SH|LFIT|)";
                var MPN1 = Regex.Replace(SHNJ, ZZZB, "");
                var PEV1 = "";
                if (MPN1.IndexOf(".")>1)
                {
                    PEV1 = MPN1.Split('.')[1];
                    if (PEV1=="00")
                    {
                        PEV1 = "01";
                    }
                }
                else
                {
                    PEV1 = MPN1[MPN1.Length - 1].ToString();
                    Regex regex = new Regex("([A-Z])");
                    if (!regex.IsMatch(PEV1))
                    {
                        PEV1 = "01";
                    }
                }
                ShuB.Rows.Add(item[8], item[3], qTY, AC12, R, "", MPN1, PEV1);
            }
            
            return ShuB;
        }
    }
}
